package com.wechat.utils;


import okhttp3.*;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.CodingErrorAction;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @author why
 * @date 2017/12/20 0020
 */
public class HttpClientUtils {
    private static final OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    /**
     * 可带参路径或不带参路径 get http 接口
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {

        Request request = new Request.Builder()
                .url(url)
                .build();
        return request(client,request);
    }

    /**
     *
     * @param url
     * @param json
     * @return
     */
    public static String postJson(String url, String json) {

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return request(client,request);
    }

    /**
     * 带参post http接口
     * @param url
     * @param parameter
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map parameter) throws IOException {

        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        Iterator iterator = parameter.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            formBodyBuilder.add(key, parameter.get(key).toString());
        }
        RequestBody requestBody = formBodyBuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }















    /**
     * http 请求动作
     * @param client
     * @param request
     * @return
     */
    public static String request(OkHttpClient client,Request request){
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return request.url()+" request error";
        }
    }
}
